package emulator.shell.commands;

import emulator.EmulatorException;
import emulator.hardware.HwNumber;
import emulator.shell.DebugShell;
import emulator.shell.ShellCommand;

public class Break implements ShellCommand {

	@Override
	public boolean execute(DebugShell shell, String[] arg)
			throws EmulatorException {
		if (arg.length < 2)
		{
			shell.getOut().println("Missing break action!");
			printHelp(shell);
		}
		else
		{
			boolean bp_enable;
			if (arg[1].equalsIgnoreCase("set"))
				bp_enable = true;
			else if (arg[1].equalsIgnoreCase("clear"))
				bp_enable = false;
			else
			{
				shell.getOut().println("Don't know how to \""+arg[1]+"\" a breakpoint");
				printHelp(shell);
				return false;
			}
			if (arg.length < 3)
			{
				shell.getOut().println("Missing address!");
				printHelp(shell);
			}
			else
			{
				try {
					int address = shell.parseAddress(arg[2]);
					shell.getCpu().breakAt(HwNumber.create(address), bp_enable);
				} catch (NumberFormatException e) {
					shell.getOut().println("Illegal argument: "+e.getMessage());
					printHelp(shell);
				}
			}
		}
		
		return false;
	}

	@Override
	public void printHelp(DebugShell shell) {
		shell.getOut().println("command syntax:");
		shell.getOut().println("break set <address>   - set breakpoint at <address>");
		shell.getOut().println("break clear <address> - remove breakpoint at <address>");
	}
}
